package zzps.exeed.kernel.core;

import zzps.exeed.kernel.tool.ResourceTool;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

public class ClassPathAbilityHolderScanner extends ClassPathScanner{

    Map<String, Set<String>> result = new LinkedHashMap<>();
    public ClassPathAbilityHolderScanner(ClassLoader classLoader) {
        super(classLoader);
    }

    public Map<String, Set<String>> scan(){
        Enumeration<URL> urlEnumeration = ResourceTool.getResources("META-INF/exeed/exeed.ability", classLoader);
        Iterator<URL> iterator = urlEnumeration.asIterator();
        while (iterator.hasNext()) {
            URL url = iterator.next();
            readAbility(url);
        }
        return result;
    }
    private void readAbility(URL url){
        try (InputStream inputStream = url.openStream()) {
            Properties properties = new Properties();
            properties.load(inputStream);
            properties.forEach((key, value) -> {
                Set<String> implementations = result.computeIfAbsent(((String) key).trim(), newKey -> new LinkedHashSet<>());
                Arrays.stream(((String) value).split(",")).map(String::trim).forEach(implementations::add);
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
